package com.tfswx.serialport.socket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tfswx.serialport.service.PrintService;
import com.tfswx.serialport.service.SerialportService;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author Ricky
 * @date 2020-07-20
 */
@Slf4j
@EqualsAndHashCode
@ServerEndpoint("/webSocket/{id}")
@Component
public class WebSocket {

    @Resource
    private SerialportService serialportService;

    public static WebSocket webSocket;

    @PostConstruct
    public void init() {
        webSocket = this;
        webSocket.serialportService = this.serialportService;
    }

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static final CopyOnWriteArraySet<WebSocket> WEB_SOCKET_SET = new CopyOnWriteArraySet<>();
    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static int onlineCount = 0;
    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 接收id
     */
    private String id = "";

    /**
     * 群发自定义消息
     */
    public static synchronized void sendInfo(String message) {
        sendInfo(null, message);
    }

    public static synchronized void sendInfo(String id, String message) {
        if (id == null) {
            for (WebSocket item : WEB_SOCKET_SET) {
                try {
                    item.sendMessage(message);
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        } else {
            for (WebSocket webSocket : WEB_SOCKET_SET) {
                if (webSocket.id.equals(id)) {
                    try {
                        webSocket.sendMessage(message);
                    } catch (IOException e) {
                        log.error(e.getMessage(), e);
                    }
                    break;
                }
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocket.onlineCount--;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) throws IOException {
        String host = session.getRequestURI().getHost();
        if ("127.0.0.1".equals(host) || "localhost".equals(host)) {
            this.session = session;
            //加入set中
            WEB_SOCKET_SET.add(this);
            //在线数加1
            addOnlineCount();
            log.info("有新窗口开始监听:" + id + ",当前在线人数为" + getOnlineCount());
            this.id = id;
        } else {
            System.out.println(host);
            session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, "不支持的Host：" + host));
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {

        //从set中删除
        WEB_SOCKET_SET.remove(this);
        //在线数减1
        subOnlineCount();
        log.info("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口" + id + "的信息:" + message);
        //群发消息
        JSONObject jsonObject = JSON.parseObject(message);
        String type = jsonObject.getString("type");
        String data = jsonObject.getString("data");
        try {
            if ("send".equals(type)) {
                webSocket.serialportService.send(data);
            } else if ("print".equals(type)) {
                PrintService.print(data);
            }
        } catch (Exception e) {
            log.error("{}：出现错误", type, e);
            JSONObject err = new JSONObject();
            err.put("type", type);
            err.put("err", e.getMessage());
            sendInfo(err.toJSONString());
        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误", error);
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public void sendMessage(Object message) throws IOException, EncodeException {
        this.session.getBasicRemote().sendObject(message);
    }
}
